//
//  WXPAuthPersonalVC.m
//  MexicoLoan
//
//  Created by WXP on 2025/2/27.
//
//

#import "WXPAuthPersonalVC.h"
#import "WXPAuthPersonalContentHeaderView.h"
#import "WXPAuthPersonalContentFooterView.h"

@interface WXPAuthPersonalVC ()

@property (nonatomic, strong) WXPAuthPersonalContentHeaderView * viewHeader;
@property (nonatomic, strong) WXPAuthPersonalContentFooterView * viewFooter;

@end

@implementation WXPAuthPersonalVC

#pragma mark - lazy
- (WXPAuthPersonalContentHeaderView *)viewHeader{
    if (!_viewHeader) {
        _viewHeader = [WXPAuthPersonalContentHeaderView new];
        WEAKSELF
        _viewHeader.blockResetAuthBtn = ^() {
            [weakSelf resetAuthBtn];
        };
        _viewHeader.emailView.blockTextFieldDidChange = ^{
            NSString *trimmedString = [weakSelf.viewHeader.emailView.tfContent.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
            weakSelf.viewHeader.emailView.tfContent.text = trimmedString;
            [weakSelf.viewFooter resetEmailHint:trimmedString];
            [weakSelf resetAuthBtn];
//            if(isInput){
//                //[GlobalMethod userBehaviorTrackWithPageName:KEY_VerifyPerson featureName:KEY_EMail_Input action:KEY_INPUT type:KEY_input];
//            }
        };
    }
    return _viewHeader;
}
- (WXPAuthPersonalContentFooterView *)viewFooter{
    if (!_viewFooter) {
        _viewFooter = [WXPAuthPersonalContentFooterView new];
        WEAKSELF
        _viewFooter.blockResetAuthBtn = ^() {
            [weakSelf resetAuthBtn];
        };
        _viewFooter.blockResetFooter = ^{
            [weakSelf resetFooterView];
        };
    }
    return _viewFooter;
}

#pragma mark - viewDidLoad
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [GlobalMethod buryPointWithPageName:KEY_VerifyPerson featureName:KEY_Page action:KEY_ENTER type:KEY_page];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [GlobalMethod buryPointWithPageName:KEY_VerifyPerson featureName:KEY_Page action:KEY_OUT type:KEY_page];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_VerifyPerson action:KEY_Enter extInfo:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navView resetViewWithTitle:@"Informacion personal"];
    [self.progressView resetViewWithNum:@"3"];
    [self.progressView.moneyView resetViewWithTag:3];
    [self resetHeaderView];
    [self resetFooterView];
    WEAKSELF
    [self.btnAuth setNoRepeatActionWithInterval:1 action:^(UIButton * _Nonnull button) {
        [NSObject clickFeedback];
        [weakSelf.btnAuth addClickAnimate];
        [weakSelf requestSubmitAuth];
    }];
    
    [self requestEducationList];
    [self requestMaritalList];
    [self requestSexList];
    [self requestGetNextStep2];
}

#pragma mark - resetHeaderView + Footer
- (void)resetHeaderView{
    self.headerView = [UIView initWithViews:@[
        self.progressView,
        [GlobalMethod getViewWithHeight:16],
        self.viewHeader,
    ]];
    self.tableView.tableHeaderView = self.headerView;
}
- (void)resetFooterView{
    UIView * view = [UIView initWithViews:@[
        self.viewFooter,
        //[GlobalMethod getViewWithHeight:(SCREEN_HEIGHT-self.btnAuth.top)],
    ]];
    self.tableView.tableFooterView = view;
}
- (void)resetAuthBtn{
    if(isStr(self.viewHeader.educationView.tfContent.text) &&
       isStr(self.viewHeader.emailView.tfContent.text) &&
       self.viewFooter.isShowEmailError == false &&
       isStr(self.viewFooter.maritalView.tfContent.text) &&
       isStr(self.viewFooter.sexView.tfContent.text) &&
       isStr(self.viewFooter.birthView.tfContent.text)){
        self.btnAuth.userInteractionEnabled = true;
        self.btnAuth.alpha = 1;
    }else{
        self.btnAuth.userInteractionEnabled = false;
        self.btnAuth.alpha = 0.5;
    }
}

#pragma mark - request
// 教育水平
- (void)requestEducationList{
    [RequestApi requestCommonDictListWithType:KEY_EDUCATION_QUALIFICATION delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        self.viewHeader.educationAry = [response arrayValueForKey:KEY_dictList];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}
// 婚姻
- (void)requestMaritalList{
    [RequestApi requestCommonDictListWithType:KEY_MARITAL_STATUS delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        self.viewFooter.maritalAry = [response arrayValueForKey:KEY_dictList];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}
// 性别
- (void)requestSexList{
    [RequestApi requestCommonDictListWithType:KEY_GENDER delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        self.viewFooter.sexAry = [response arrayValueForKey:KEY_dictList];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}
// 获取相关个人信息 - 填充到输入框
- (void)requestGetNextStep2{
    [RequestApi requestGetNextStepNewWithDelegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        NSDictionary * personInfo = [response dictionaryValueForKey:KEY_personInfo];
        NSString * sex = [personInfo stringValueForKey:KEY_sex];
        NSString * birthday = [personInfo stringValueForKey:KEY_birthday];
        if(isStr(sex)){
            self.viewFooter.sexView.tfContent.text = [sex isEqualToString:@"H"]?@"Hombre":@"Mujer";
            self.viewFooter.gender = [sex isEqualToString:@"H"]?@"1":@"2";
            [GlobalMethod hitPointWithPageName:KEY_VerifyPerson action:KEY_Gender_Focus extInfo:nil];
        }
        if(isStr(birthday)){
            BOOL isInRange = [self isAgeInRangeWithTime:birthday lowerAge:18 upperAge:45 dateFormat:TIME_DAY_MONTH_YEAR];
            self.viewFooter.birthView.tfContent.text = isInRange?birthday:@"";
            if (isInRange == true){
                [GlobalMethod hitPointWithPageName:KEY_VerifyPerson action:KEY_Birthday_Focus extInfo:nil];
            }
        }
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

// 判断字符串 是否在年龄范围内
- (BOOL)isAgeInRangeWithTime:(NSString *)dateString lowerAge:(NSInteger)lowerAge upperAge:(NSInteger)upperAge dateFormat:(NSString *)dateFormat{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:dateFormat];
    NSDate *date = [dateFormatter dateFromString:dateString];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *ageComponents = [calendar components:NSCalendarUnitYear fromDate:date toDate:[NSDate date] options:0];
    NSInteger age = [ageComponents year];
    return (age >= lowerAge && age <= upperAge);
}

- (void)requestSubmitAuth{
    [GlobalMethod hitPointWithPageName:KEY_VerifyPerson action:KEY_Save_Start extInfo:nil];
    NSDictionary * dic = @{
        KEY_educationQualification: readStr(self.viewHeader.educationQualification),
        KEY_maritalStatus: readStr(self.viewFooter.maritalStatus),
        KEY_gender: readStr(self.viewFooter.gender),
        KEY_email: readStr(self.viewHeader.emailView.tfContent.text),
        KEY_birth: readStr(self.viewFooter.birthView.tfContent.text),
    };
    [RequestApi requestSaveUserInfoWithData:dic step:KEY_PERSONAL_INFO delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        [GlobalMethod hitPointWithPageName:KEY_VerifyPerson action:KEY_Save_End extInfo:nil];
        // 调用获取下一步接口，跳转到该接口返回的对应认证页面
        [self requestGetNextStep];
        
        // 风控埋点
        [GlobalMethod addRiskControlWithType:KEY_INFORMATION startTime:self.startTime endTime:[GlobalMethod getTimeStampMillisecond]];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

@end
